#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "yaffs_ioctl.h"

int main(int argc, char *argv[]) {
    char level[ARG_LENGTH];
    char pass1[ARG_LENGTH];
    char pass2[ARG_LENGTH];
    char level_id[ARG_LENGTH];
    int level_num = 0;
    int fd = -1;
    int return_value;
    struct termios oldt, newt;
    
    if ((fd = open("/dev/defy", O_RDWR)) < 0) {
	printf("DEFY not installed\n");
	return -1;
    }

    if(argc > 2) {
	strcpy(level, argv[1]);
	if(ioctl(fd, SET_LEVEL_ID, level) < 0) {
	    perror("Level ID");
	    return -1;
	}
	strcpy(pass1, argv[2]);
	if(ioctl(fd, SET_PASSWORD, pass1) < 0) {
	    perror("Password");
	    return -1;
	}
    } else {    
	printf("Enter credentials:");
	printf("\n         Level ID: ");
	scanf("%s", level);
	if(ioctl(fd, SET_LEVEL_ID, level) < 0) {
	    perror("Level ID");
	    return -1;
	}
	
	// Set environment to not echo credential entry
	tcgetattr(STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~ECHO;
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);
	
	printf("         Password: ");
	scanf("%s", pass1);
	printf("\n");
	
	printf("Re-enter Password: ");
	scanf("%s", pass2);
	printf("\n");
	
	// Return to original environment
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	
	if(!strcmp(pass1, pass2)) {
	    if(ioctl(fd, SET_PASSWORD, pass1) < 0) {
		perror("Password");
		return -1;
	    }
	} else {
	    memset(pass1, 0, ARG_LENGTH);
	    memset(pass2, 0, ARG_LENGTH);
	    printf("Passwords do not match\n");
	    return -1;
	}
    }

    memset(level, 0, ARG_LENGTH);
    memset(pass1, 0, ARG_LENGTH);
    memset(pass2, 0, ARG_LENGTH);

    if(!ioctl(fd, GET_OPEN_LEVELS, level_id)) {
	printf("Creating a master level\n");
    } else {
	printf("Below which level would you like the new level to reside?\n");
	for(level_num = 0; strcmp(level_id, "\0"); level_num++) {
	    printf("%d: %s\n", level_num, level_id);
	    ioctl(fd, GET_OPEN_LEVELS, level_id);
	}
	printf("\n: ");
	scanf("%d", &level_num);
	printf("Creating a level below %d\n", level_num);
	if(ioctl(fd, SET_PREV_LEVEL, level_num)) {
	    perror("Level Number");
	    return -1;
	}
    }

    if(ioctl(fd, CREATE_LEVEL) < 0) {
	perror("Create");
	return -1;
    }
    
    return 0;
}
